﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public class PB_RackBusiness : BaseBusiness<PB_Rack>, IPB_RackBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_RackBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_Rack>> GetDataListAsync(PB_RackPageInput input)
        {
            var q = GetIQueryable().Where(w => w.AreaId == input.AreaId);
            var where = LinqHelper.True<PB_Rack>();
            var search = input.Search;
            //q = q.Include(i => i.PB_Storage);去除了外键关联，故先注销此关联

            if (!search.Keyword.IsNullOrEmpty())
            {
                search.Keyword = search.Keyword.Trim();
                //if (!search.Keyword.IsNullOrEmpty())
                where = where.And(w => w.Name.Contains(search.Keyword) || w.Code.Contains(search.Keyword));
            }
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_Rack> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataAddLog(UserLogType.仓库管理, "Name", "货架")]
        public async Task AddDataAsync(PB_Rack data)
        {
            var q = await Db.GetIQueryable<PB_Rack>().Where(x => x.AreaId == data.AreaId && x.Code == data.Code).FirstOrDefaultAsync();
            if (q == null)
            {
                data.QrCode = h_Rack + "," + data.Id;
                await InsertAsync(data);
            }
            else
            {
                throw new BusException("货架编号已存在");
            }
        }

        [DataEditLog(UserLogType.仓库管理, "Name", "货架")]
        public async Task UpdateDataAsync(PB_Rack data)
        {
            var q = await Db.GetIQueryable<PB_Rack>().Where(x => x.AreaId == data.AreaId && x.Id == data.Id).FirstOrDefaultAsync();
            if (q.Code == data.Code)
            {
                data.QrCode = h_Rack + "," + data.Id;
                await UpdateAsync(data);
            }
            else
            {
                var q2 = await Db.GetIQueryable<PB_Rack>().Where(x => x.AreaId == data.AreaId && x.Code == data.Code).ToListAsync();
                if (q2.Count() < 1)
                {
                    data.QrCode = h_Rack + "," + data.Id;
                    await UpdateAsync(data);
                }
                else
                {
                    throw new BusException("货架编号已存在");
                }
            }
            
        }

        [DataDeleteLog(UserLogType.仓库管理, "Name", "货架")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            List<PB_Location> LocationList = await Db.GetIQueryable<PB_Location>().Where(x => ids.Contains(x.RackId)).ToListAsync();
            if (LocationList.Count > 0)
            {
                throw new BusException("货架下有货位禁止删除");
            }
            await DeleteAsync(ids);
        }

        public async Task<List<PB_Rack>> QueryRackDataAsync()
        {
            var q = GetIQueryable();
     
            return await q.ToListAsync();
        }

        public async Task<PageResult<PB_Rack>> GetDataListAsync(PageInput<PB_RackConditionDTO> input,string areaId)
        {
            var q = GetIQueryable();
            var search = input.Search;
            if (!areaId.IsNullOrEmpty()) {
                q = q.Where(m => m.AreaId == areaId);
            }
          
            return await q.GetPageResultAsync(input);
        }

        public async Task<PageResult<PB_Rack>> GetDataListAsyncid(PB_RackPageInput input, string id)
        {
            var q = GetIQueryable().Where(w => w.AreaId == input.AreaId);
            var where = LinqHelper.True<PB_Rack>();
            var search = input.Search;
            //q = q.Include(i => i.PB_Storage);去除了外键关联，故先注销此关联

            if (!search.Keyword.IsNullOrEmpty())
            {
                search.Keyword = search.Keyword.Trim();
                //if (!search.Keyword.IsNullOrEmpty())
                where = where.And(w => w.Name.Contains(search.Keyword) || w.Code.Contains(search.Keyword));
            }
            q = q.Where(m=>m.Id==id);
            return await q.Where(where).GetPageResultAsync(input);
        }

        public  async Task<AjaxResult> SelectRackID(PB_RackPrint data, MongoDBOptions _mongodbOptions)
        {
             try
            {
                int i = 0;
                List<string> List = new List<string>();
                foreach (var item in data.RackID)
                {
                    List.Add(item);
                    i = List.Count;
                }
                string timestamp = GetTimeStamp();
                var q = GetIQueryable();
                List<PrintQueue> printqueue = new List<PrintQueue>();
                var res = q = q.Where(m => List.Contains(m.Id));
                var k = await Db.GetIQueryable<Base_Department>().Where(m => m.Id == _operator.Property.DepartmentId).FirstOrDefaultAsync();
                string strguid = Guid.NewGuid().ToString("N");
                foreach (var item in res)
                {
                    DataTable de = await Db.GetDataTableWithSqlAsync("select Name from PB_StorArea where Id='"+item.AreaId + "' Limit 1");
                    //var de = await Db.GetIQueryable<PB_StorArea>().Where(m => m.Id ==item.AreaId).FirstOrDefaultAsync();
                    PB_Rack Location = new PB_Rack();
                    PrintQueue printdata = new PrintQueue();
                    printdata.Id = IdHelper.GetId();
                    printdata.No = item.Id;//编号
                    printdata.Name = de.Rows[0][0].ToString()+"/" +item.Name;
                    printdata.TypeName = "打印货架";
                    printdata.Date =DateTime.Now.ToString("yyyy-MM-dd");//生产日期当前时间
                    printdata.Dept = k.Name;//当前登录人所在组织
                    printdata.QrCode = item.QrCode;//货架
                    printdata.Type = Skill_Type.Rack.ToString();//货架
                    printdata.Status = "0";
                    printdata.Printer =data.PrintID;
                    printdata.BatchNumber = strguid;
                    printdata.IsProduct = false;
                    printdata.JobCount =i;
                    printdata.Code = item.Code;
                    printqueue.Add(printdata);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, printqueue);
                AjaxResult resIn = new AjaxResult
                {
                    Success = true,
                    Msg = "打印成功"
                };
                return  resIn;
            }
            catch (Exception)
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg = "打印失败！数据错误请检查数据"
                };
                return res;
            }
        }

        public  async Task<List<RacklistDto>> Selectid(string id)
        {
            Expression<Func<PB_Rack, PB_StorArea, RacklistDto>> select = (a, b) => new RacklistDto
            {
                AreaName = b.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_StorArea>() on a.AreaId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            string[] arr = id.Split(',');
            List<string> List = new List<string>();
            foreach (var item in arr)
            {
                List.Add(item);

            }
            q = q.Where(m => List.Contains(m.Id));
            return await q.ToListAsync();
        }

        public async Task<List<PB_Rack>> QueryRackDataAsyncareaid(string areaid)
        {
            var q = GetIQueryable();
            q = q.Where(m=>m.AreaId==areaid);
            return await q.ToListAsync();
        }

        #endregion

        #region 私有成员

        #endregion
    }
}